#include "volume.h"
#include "ui_volume.h"
#include <QMouseEvent>

Volume::Volume(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Volume)
{
    ui->setupUi(this);
    setWindowFlag(Qt::Popup); // 将音量调节窗口设置为弹出窗口
    // 安装拦截器
    ui->volumeBox->installEventFilter(this);
}

Volume::~Volume()
{
    delete ui;
}

bool Volume::eventFilter(QObject *watched, QEvent *event)
{
    if(ui->volumeBox == watched)
    {
        // 鼠标按下事件
        if(event->type() == QEvent::MouseButtonPress)
        {
            calcVolume();
        }
        else if(event->type() == QEvent::MouseButtonRelease)
        {
            // 鼠标释放
            emit setVolume(volume);
        }
        else if(event->type() == QEvent::MouseMove)
        {
            calcVolume();
            emit setVolume(volume);
        }
        return true;
    }
    return QObject::eventFilter(watched, event);
}

void Volume::calcVolume()
{
    // 获取鼠标的纵坐标
    int y = ui->volumeBox->mapFromGlobal(QCursor().pos()).y();

    // 验证y的正确性？
    y = y < 5 ? 5 : y;
    y = y > 150 ? 150 : y;

    // 更新outLine的高度
    ui->outLine->setGeometry(ui->outLine->x(), y, ui->outLine->width(), 150 - y);

    // 更新volumeBox的位置
    int volumeBtnY = ui->outLine->y() - ui->volumeBtn->height() / 2;
    if(volumeBtnY > 140)
    {
        volumeBtnY = 140;
    }
    ui->volumeBtn->move(ui->volumeBtn->x(), volumeBtnY);

    // 计算音量大小
    volume = ui->outLine->height() / (double)145 * 100;

}





